'use strict';

/**
 * 菜单模型
 * @param app
 */
module.exports = app => {
  const { STRING, INTEGER, BOOLEAN, DATE, TEXT, BIGINT } = app.Sequelize;

  const Menu = app.model.define('sys_menus', {
    id: {
      type: BIGINT,
      primaryKey: true,
      comment: '菜单ID',
    },
    parentId: {
      type: BIGINT,
      allowNull: true,
      defaultValue: 0,
      comment: '父菜单ID',
      field: 'parent_id',
    },
    name: {
      type: STRING(50),
      allowNull: false,
      comment: '菜单名称',
      field: 'name',
    },
    path: {
      type: STRING(255),
      allowNull: true,
      comment: '路由路径',
      field: 'path',
    },
    component: {
      type: STRING(255),
      allowNull: true,
      comment: '组件路径',
      field: 'component',
    },
    icon: {
      type: STRING(100),
      allowNull: true,
      comment: '图标',
      field: 'icon',
    },
    type: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 1,
      comment: '菜单类型：1目录，2菜单，3按钮',
      field: 'type',
    },
    permission: {
      type: STRING(100),
      allowNull: true,
      comment: '权限标识',
      field: 'permission',
    },
    sort: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '排序',
      field: 'sort',
    },
    visible: {
      type: BOOLEAN,
      defaultValue: true,
      comment: '是否显示：true显示，false隐藏',
      field: 'visible',
    },
    status: {
      type: BOOLEAN,
      defaultValue: true,
      comment: '状态：true启用，false禁用',
      field: 'status',
    },
    createTime: {
      type: DATE,
      allowNull: false,
      comment: '创建时间',
      field: 'create_time',
      defaultValue: app.Sequelize.NOW,
    },
    updateTime: {
      type: DATE,
      allowNull: false,
      comment: '更新时间',
      field: 'update_time',
      defaultValue: app.Sequelize.NOW,
    },
  });

  // 关联关系
  Menu.associate = function() {
    // 自关联：父菜单
    app.model.Menu.belongsTo(app.model.Menu, {
      foreignKey: 'parent_id',
      as: 'parent',
    });
    // 自关联：子菜单
    app.model.Menu.hasMany(app.model.Menu, {
      foreignKey: 'parent_id',
      as: 'children',
    });
    // 关联角色（通过角色菜单关联表）
    app.model.Menu.belongsToMany(app.model.Role, {
      through: app.model.RoleMenu,
      foreignKey: 'menuId',   // 使用RoleMenu模型中定义的字段名
      otherKey: 'roleCode',  // 使用RoleMenu模型中定义的字段名
      targetKey: 'code', // 指定Role模型的目标键为code
      as: 'roles',
    });
  };

  // 在创建前生成雪花ID
  Menu.beforeCreate((menu) => {
    const SnowflakeUtil = require('../utils/snowflake');
    menu.id = SnowflakeUtil.generateSnowflakeId();
  });

  // 自定义toJSON方法，避免字段重复
  Menu.prototype.toJSON = function() {
    const values = Object.assign({}, this.get());
    // 移除重复的下划线字段
    delete values.create_time;
    delete values.update_time;
    delete values.parent_id;
    return values;
  };

  return Menu;
};